package tools.gis.antennaReader;

import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;
import java.util.Vector;

import datatypes.Antenna;
import datatypes.AntennaType;
import datatypes.FrequencyRange;

/**
 * Site (locatie) met daarin alle antennes op die site
 * Bevat een default antenne per site: indien geen antennes op een site
 * wordt de default teruggegeven.
 * 
 * @author Bart Moens
 */
public class AntennaSite {

	double x;
	double y;
	
	Antenna defaultAntenna;
	
	LinkedList<Antenna> antennaList = new LinkedList<Antenna>();
	
	public AntennaSite(double x, double y, Antenna defaultAntenna) {
		this.x = x;
		this.y = y;
		this.defaultAntenna = defaultAntenna;
	}
	
	public void addAntenna(Antenna a) {
		antennaList.add(a);
	}
	
	public LinkedList<Antenna> getAntennas() {
		if (antennaList.size() == 0) {
			antennaList.add(defaultAntenna);
		}
		return antennaList;
	}
	
	public double getX() {
		return x;
	}

	public double getY() {
		return y;
	}
	
	public void filterOnOperator(String operator) {
		for (Antenna a : antennaList) {
			if (!a.getOperator().toLowerCase().equals(operator.toLowerCase())){
				antennaList.remove(a);
				filterOnOperator(operator);
				return;
			}
		}		
		for (Antenna a : antennaList) {
			a.setOperatorSite(true);
		}		
		defaultAntenna.setOperator(operator);
	}

	public void filterOnFrequency(Vector<FrequencyRange> range) {
		for (Antenna a : antennaList) {
			double freq = a.getFrequency();
			boolean remove = true;
			for (FrequencyRange fr : range) {
				if (fr.isBetween(freq))
					remove = false;
			}
			if (remove) {
				antennaList.remove(a);
				filterOnFrequency(range);
				return;
			}
		}		
		defaultAntenna.setFrequency(range.get(0).mean());
	}
	
	
	public void transformToOmniAntennas(Vector<FrequencyRange> range) {
		//allow only one antenna per frequency
		Set<Double> s = new HashSet<Double>();
		for (Antenna a : antennaList) {
			double freq = a.getFrequency();
			for (FrequencyRange fr : range) {
				if (fr.isBetween(freq)) {
					a.setFrequency(fr.mean());
					freq = fr.mean();
				}
			}
			
			
			if (!s.add(new Double(freq))) {
				antennaList.remove(a);
				transformToOmniAntennas(range);
				return;
			}
		}	
		for (Antenna a : antennaList) {
			a.setType(AntennaType.omnidirectional);
		}	
		defaultAntenna.setType(AntennaType.omnidirectional);
	}
	
	public String toString() {
		String s = "Antennasite @ " + x + "-" + y + "\n";

		for (Antenna a : getAntennas()) {
			s += a.toString() + "\n";
		}	
		return s;
	}

}
